package com.yuma.tingshu.search.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration("searchThreadPoolConfigClass")
/**
 * @ConfigurationProperties(prefix = "threadPool")
 * Spring Boot 要求 @ConfigurationProperties 的 prefix 必须是“规范形式（canonical form）”，
 * 即：✅ 全部小写 + 使用短横线分隔（kebab-case）
 */
//@ConfigurationProperties(prefix = "thread-pool")
public class ThreadPoolConfig {

    @Value("${thread-pool.corePoolSize}")
    private Integer corePoolSize;
    @Value("${thread-pool.maximumPoolSize}")
    private Integer maximumPoolSize;
    @Value("${thread-pool.keepAliveTime}")
    private Integer keepAliveTime;
    @Value("${thread-pool.workQueueSize}")
    private Integer workQueueSize;

    @Bean("searchThreadPoolConfig")
    public ExecutorService executorService() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        // 设置核心参数
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maximumPoolSize);
        executor.setKeepAliveSeconds(keepAliveTime);
        executor.setQueueCapacity(workQueueSize);

        // 设置线程名前缀，便于调试
        executor.setThreadNamePrefix("ContextAware-");

        // ⭐⭐⭐⭐⭐ 关键：设置 TaskDecorator，自动传递 RequestContextHolder 上下文
        executor.setTaskDecorator(runnable -> {
            // 在提交任务时，捕获当前线程的 RequestAttributes
            RequestAttributes context = RequestContextHolder.currentRequestAttributes();
            return () -> {
                try {
                    // 在异步线程中重新绑定上下文
                    RequestContextHolder.setRequestAttributes(context, true);
                    runnable.run(); // 执行原任务
                } finally {
                    // 清理上下文，避免内存泄漏
                    RequestContextHolder.resetRequestAttributes();
                }
            };
        });

        // 初始化线程池（必须调用）
        executor.initialize();

        // 返回的是 ExecutorService 接口，兼容你原有代码
        return executor.getThreadPoolExecutor();
    }
}